// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require(CONFIG.BasePath + "js/enterprise/base");
	var router = require("../hash/pageRouter");
	var constant = require("constant");
	var css_pickup = require("./accountPickup.css");
	var databind = require("databind");
	var tools = require("tools");
	var financeId;
	var financeState;
	var productType;
	var flag = true;
	var pickupMethod;
	var deliveryMethod;
	var quantities = [];
	var inventoryIds = [];
	var bulkstockIds = [];
	var units = [];
	var caseQuantities = [];
	var deliveryDate;
	var deliveryAddress;
	var financeNumber;
	var valuationCal = require("valuationCal");
	var remark;
	var str1 = ['<span class="pickupTitle">添加新货箱：</span><a class="addInventory" style="float: right;" href="javascript:void(0);">添加</a><label for="exchangeInventoryFileUuid" class="importInventory" style="float: right; margin-left: 15px; margin-right:15px;">导入</label><a target="_blank" style="float: right;" href="../excelTemplate/template.xls">导入模板下载</a>',
'			<table>',
'				<tr>',
'					<th style="padding-left: 17px;">货物</th>',
'					<th>重量(吨)</th>',
'					<th>物流运单号</th>',
'					<th>箱号</th>',
'					<th>操作</th>',
'				</tr>',
'				<tr>',
'					<td style="padding-left: 17px;">',
'						1<select name="bulkstockInfoId" class="bulkstockSelector"></select>',
'					</td>',
'					<td><input isNull="1" codeName="重量" name="weight" type="text" /></td>',
'					<td><input isNull="1" codeName="物流运单号" class="upper" name="waybillNumber" type="text" /></td>',
'					<td><input isNull="1" codeName="箱号" class="upper" name="caseNumber" type="text" /></td>',
'					<td></td>',
'				</tr>',
'			</table>'].join("");

	var str3 = ['<span class="pickupTitle">添加新货物：</span><a class="addBulkstock" style="float: right;" href="javascript:void(0);">添加</a>',
'			<table>',
'				<tr>',
'					<th style="padding-left: 17px;">货物</th>',
'					<th>生产厂家</th>',
'					<th>产地</th>',
'					<th>重量(吨)</th>',
'					<th>估值</th>',
'					<th>操作</th>',
'				</tr>',
'				<tr>',
'					<td style="padding-left: 17px;">',
'						<select name="bulkstockInfoId" class="bulkstockSelector"></select>',
'					</td>',
'					<td><input isNull="1" codeName="生产厂家" name="manufacturer" type="text" /></td>',
'					<td><input isNull="1" codeName="产地" name="originPlace" type="text" /></td>',
'					<td><input isNull="1" codeName="重量" name="weight" type="text" /></td>',
'					<td><input type="hidden" name="bulkstockPrice" /><input isNull="1" codeName="估值" class="bValuation" readonly="readonly" type="text" /><a class="valuation" href="javascript:void(0);">估值</a></td>',
'					<td></td>',
'				</tr>',
'			</table>'].join("");

	var str2 = '<span class="pickupTitle">提货申请资料：</span><input type="file" name="file" id="fileUuids" class="none" />'+
				'<input type="hidden" name="fileUuids"/>'+
				'<span class="fs"></span>'+
				'<label for="fileUuids" class="fileUuids">添加</label>';

	var init = function(page) {
		financeId = page.params.financeId;
		financeNumber = page.params.financeNumber;
		inquireFinanceApplicationDetail();
		router.init();
		initEvent();
		loadLoanData($("#accountPickup #loanNoticeId"));
	};

	var initEvent = function() {
		if (base.getData("sid") == null) {
			location.href = "../login/login.html";
		}
		
		$("#accountPickup").on("change", "#exchangeInventoryFileUuid", function(){
			tools.uploadFile("exchangeInventoryFileUuid", function(data){
				importExchangeInventory(data.data[0].fileUuid);
			});
		});
		
		$("#accountPickup").on("click", ".deleteProductIntro", function(){
			$(this).parent().remove();
			var fileUuid = [];
			for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
				fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
			}
			$("#accountPickup input[name=fileUuids]").val(fileUuid);
		});
		
		$("#accountPickup").on("keyup", "input[name=weight]", function(){
			tools.clearNoNum(this);
		});
		
		$("#accountPickup").on("click", ".checkeds", function(){
			$("#inventoryIds").html("");
			$("#inventoryIds").append('<input type="hidden" name="financeId" value="'+financeId+'" />');
			$.each($("#accountPickup .checkeds:checked"), function() {
				var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
				$("#inventoryIds").append(str);
			});
		});
		
		if($(".pickupMethod:checked").val() == 1){
			$(".interestArea").removeClass("none");
			$("#changeInventory").html("");
			$("#changeBulkstock").html("");
			if (productType == 2) {
				$(".checkeds").removeClass("none");
			} else {
				$(".checkeds").addClass("none");
			}
			
			$.each($(".checkeds[disabled!=disable][checked=checked]"), function(){
				var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
				$("#inventoryIds").append(str);
			});
		}
		
		$(".deliveryMethod").unbind("click").click(function(){
			if ($(".deliveryMethod:checked").val() == 1) {
				$("#deliveryDate").attr({"isNull": "1", "codeName": "配送时间"});
				$("#deliveryAddress").attr({"isNull": "1", "codeName": "配送地址"});
			} else {
				$("#deliveryDate").attr({"isNull": "0"});
				$("#deliveryAddress").attr({"isNull": "0"});
			}
		});
		
		$(".hidePick").unbind("click").click(function(){
			$(".checkeds[disabled=disabled]").parents("tr").toggle(1000);
		});
		
		//箱号输入框改变事件
		$("#changeInventory").on("change", "input[name=caseNumber]", function(){
			var $this = $(this);
			tools.matchs(/^[a-zA-Z]{4}[0-9]{7}$/, $this.val(), "请输入正确的箱号！");
		});

		//点击项目基本详情financeDetail
		$(".financeDetail").unbind("click").click(function() {
			router.route("account/accountDetail.html?financeId=" + financeId + "&financeNumber=" + financeNumber, true);

		});

		if ($("#accountPickup #bulkstockInventoryBody tr").length == 1) {
			$("#accountPickup .pickupForm").html('<div class="emptyData">暂无可提货物！</div>');
		}

		$("#accountPickup .pickupNav a").unbind("click").click(function() {
			$("#accountPickup .pickupNav a").removeClass("pickupNavActive");
			$(".pickupTab").addClass("none");
			$("." + $(this).attr("pickupTab")).removeClass("none");

			$(this).addClass("pickupNavActive");
		});

		$("#deliveryDate").on("blur", function() {
			var pickTab = $(".pickupNavActive").attr("pickupTab");
			
			calculateInterest($("#deliveryDate").val());
			
			//计算费用
			if ($("#deliveryDate").val() != "") {
				var price = 0;
				var value = 0;
				var interest = 0;
				var expense = 0;
				calculateInterest($("#deliveryDate").val());
			}
		});
		
		$("#pickInventory").unbind("click").click(function() {
			if (flag) {
				inquireBulkstockInventoryPageList();
				flag = false;
			}
		});

		$(".pickupMethod").unbind("click").click(function() {
			if($(".pickupMethod:checked").val() == 1){
				$(".interestArea").removeClass("none");
				$("#accountPickup .pickupFile").html("");
				$("#inventoryIds").html("");
				$("#inventoryIds").append('<input type="hidden" name="financeId" value="'+financeId+'" />');
				$("#changeInventory").html("");
				$("#changeBulkstock").html("");
				$(".checkeds").prop("checked", true);
				$(".checkeds:disabled").prop("checked", false);
				if (productType == 2) {
					$(".checkeds").removeClass("none");
				} else {
					$(".checkeds").addClass("none");
				}
				if ($(".checkeds[disabled!=disable]:checked").length == $(".checkeds[disabled!=disable]").length){
					$("#accountPickup .checkAll").prop("checked", true);
				} else {
					$("#accountPickup .checkAll").prop("checked", false);
				}
				$.each($(".checkeds[disabled!=disable]"), function(){
					var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
					$("#inventoryIds").append(str);
				});
				
				//计算费用
				if ($("#deliveryDate").val() != "") {
					calculateInterest($("#deliveryDate").val());
				}
			} else if ($(".pickupMethod:checked").val() == 2) {
				$(".interestArea").addClass("none");
				$("#accountPickup .pickupFile").html("");
				$(".checkeds").attr("checked", false);
				$("#inventoryIds").html("");
				$("#inventoryIds").append('<input type="hidden" name="financeId" value="'+financeId+'" />');
				$("#changeInventory").html("");
				$("#changeBulkstock").html(str3);
				$(".checkeds").removeClass("none");
				tools.loadBulkstockData($("#changeBulkstock .bulkstockSelector"));
				
				$(".addBulkstock").unbind("click").click(function(){
					var s = '<tr><td style="padding-left: 17px;"><select name="bulkstockInfoId" class="bulkstockSelector"></select></td><td><input isNull="1" codeName="生产厂家" type="text" name="manufacturer" /></td><td><input isNull="1" codeName="产地" type="text" name="originPlace" /></td><td><input isNull="1" codeName="重量" type="text" name="weight" /></td><td><input readonly="readonly" type="text" class="bValuation" /><input type="hidden" isNull="1" codeName="估值" name="bulkstockPrice" /><a class="valuation" href="javascript:void(0);">估值</a></td><td><a href="javascript:void(0);" class="delete">删除</a></td></tr>';
					$("#changeBulkstock table").append(s);
					tools.loadBulkstockData($("#changeBulkstock .bulkstockSelector:last"));
				});
				
				$("#changeBulkstock").on("click", ".valuation", function(){
					valuationCal.showCal("货物估值", $(this).parents("tr").find(".bulkstockSelector").val(), "重量" , $(this).parents("tr").find("input[name=weight]").val(), $(this).parents("tr").find(".bValuation"), $(this).parents("tr").find("input[name=bulkstockPrice]"), 1);
				});
				
				$("#changeBulkstock").on("click", ".delete", function(){
					$(this).parents("tr").remove();
				});
			} else {
				$(".interestArea").addClass("none");
				$("#accountPickup .pickupFile").html(str2);
				$("#accountPickup").on("change", "#fileUuids", function(){
					tools.uploadFile("fileUuids", function(data){
						var str = '<div class="showProductIntroDiv"><a target="_blank" class="mas" fileUuid="' + data.data[0].fileUuid + '" href="/finance/api/v1.0/downloadFile.file?fileUuid=' + data.data[0].fileUuid + '" class="showProductIntro">' + data.data[0].fileName + '</a>&nbsp;&nbsp;&nbsp;&nbsp;<a class="deleteProductIntro">x</a></div>';
						$("#accountPickup .fileUuids").before(str);
						var fileUuid = [];
						for (var j = 0; j < $(".showProductIntroDiv .mas").length; j++) {
							fileUuid.push($($(".showProductIntroDiv .mas")[j]).attr("fileUuid"));
						}
						$("#accountPickup input[name=fileUuids]").val(fileUuid);
					});
				});
				$(".checkeds").attr("checked", false);
				$("#inventoryIds").html("");
				$("#inventoryIds").append('<input type="hidden" name="financeId" value="'+financeId+'" />');
				$("#changeInventory").html(str1);
				$("#changeBulkstock").html("");
				$(".checkeds").removeClass("none");
				tools.loadBulkstockData($("#changeInventory .bulkstockSelector"));
				
				$(".checkeds").unbind("click").click(function(){
					$("#inventoryIds").html("");
					$("#inventoryIds").append('<input type="hidden" name="financeId" value="'+financeId+'" />');
					$.each($("#accountPickup .checkeds:checked"), function() {
						var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
						$("#inventoryIds").append(str);
					});
				});
				
				$(".addInventory").unbind("click").click(function(){
					var s = '<tr><td style="padding-left: 17px;">' + $("#changeInventory tr").length + '<select name="bulkstockInfoId" class="bulkstockSelector"></select></td><td><input isNull="1" codeName="重量" name="weight" type="text" /></td><td><input class="upper" isNull="1" codeName="物流运单号" class="upper" name="waybillNumber" type="text" /></td><td><input isNull="1" class="upper" codeName="箱号" name="caseNumber" type="text" /></td><td><a href="javascript:void(0);" class="delete">删除</a></td></tr>';
					$("#changeInventory table").append(s);
					tools.loadBulkstockData($("#changeInventory .bulkstockSelector:last"));
				});
				
				$("#changeInventory").on("click", ".delete", function(){
					$(this).parents("tr").remove();
				});
			}
		});

		$("#pickupSubmit").unbind("click").click(function() {
			if ($("#inventoryIds input[name=inventoryIds]").length == 0) {
				base.alert(2, "请勾选货箱!");
				return;
			}
			databind.submitDom($("#accountPickup"), function(){
				router.route("account/accountDetail.html?financeId=" + financeId);
			});
		});
	};
	
	//放款批次下拉框
	var loadLoanData = function(dom) {
		base.fnAjax({
			action: "inquireLoanNoticePageList.json",
			async: false,
			oData: {
				financeId: financeId,
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					$(dom).html("");
					$.each(data.datas, function(i, v) {
						$(dom).append('<option value=' + this.loanNoticeId + '>' + this.createDateTime + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};
	
	//导入换箱EXCEL
	var importExchangeInventory = function(fileUuid) {
		base.fnAjax({
			action: "importExchangeInventory.json",
			async: false,
			oData: {
				fileUuid: fileUuid
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					$.each(data.datas, function() {
						var _this = this;
						var s = '<tr><td style="padding-left: 17px;">' + $("#changeInventory tr").length + '<select name="bulkstockInfoId" class="bulkstockSelector"></select></td><td><input isNull="1" codeName="重量" name="weight" type="text" /></td><td><input isNull="1" codeName="物流运单号" class="upper" name="waybillNumber" class="upper" type="text" /></td><td><input isNull="1" class="upper" codeName="箱号" name="caseNumber" type="text" /></td><td><a href="javascript:void(0);" class="delete">删除</a></td></tr>';
						
						if ($("#changeInventory tr:last").find("input[name=weight]").val() == "" && $("#changeInventory tr:last").find("input[name=caseNumber]").val() == "" && $("#changeInventory tr:last").find("input[name=waybillNumber]").val() == "") {
							databind.fillForm($("#changeInventory tr:last"), _this);
						} else {
							$("#changeInventory table").append(s);
							tools.loadBulkstockData($("#changeInventory .bulkstockSelector:last"));
							databind.fillForm($("#changeInventory tr:last"), _this);
						}
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};
	
	//利息计算
	var calculateInterest = function(cutoffDate) {
		var checkeds = [];
		$.each($("#accountPickup .checkeds:checked"), function() {
			checkeds.push($(this).attr("inventoryId"));
		});
		var interestEstimation = interestEstimationFinanceInventory($("#deliveryDate").val(), checkeds, financeId);
		$("#accountPickup .estimateAmount").html(interestEstimation.summation);
		$("#accountPickup input[name=estimateAmount]").val(interestEstimation.summation);
		$("#accountPickup .value").html(interestEstimation.principal);
		$("#accountPickup .interest").html(interestEstimation.interest);
		$("#accountPickup .interestOrigin").html(interestEstimation.interestOrigin);
		$("#accountPickup .expense").html(interestEstimation.expense);
	}

	//利息估算-指定货箱
	var interestEstimationFinanceInventory = function(cutoffDate, inventoryIds, financeId) {
		var interestEstimation = {
			summation: 0,
			interest: 0,
			principal: 0,
			expense: 0
		};
		base.fnAjax({
			action: "interestEstimationFinanceInventory1.json",
			async: false,
			oData: {
				cutoffDate: cutoffDate,
				inventoryId: inventoryIds,
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					//本息合计
					interestEstimation.summation = data.datas[0].summation;
					//利息
					interestEstimation.interest = data.datas[0].interest;
					//原利息
					interestEstimation.interestOrigin = data.datas[0].interestOrigin;
					//本金
					interestEstimation.principal = data.datas[0].principal;
					//其他费用
					interestEstimation.expense = data.datas[0].expense;
				} else {
					//					base.alert(2, "信息获取失败");
				}
			}
		});
		return interestEstimation;
	};

	//查询融资信息详情
	var inquireFinanceApplicationDetail = function() {
		base.fnAjax({
			action: "inquireFinanceApplicationDetail.json",
			async: false,
			oData: {
				financeId: financeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var dm = data.datas[0].deliveryMethod;
					productType = data.datas[0].productType;
					if (2 == dm || 3 == dm) {
						$("#accountPickup .deliveryMethod[value=2]").attr("checked", "checked");
					} else {
						$("#accountPickup .deliveryMethod[value=1]").attr("checked", "checked");
						$("#deliveryAddress").val($.trim(data.datas[0].deliverProvince) + $.trim(data.datas[0].deliverCity) + $.trim(data.datas[0].deliverDistrict) + $.trim(data.datas[0].deliverAddress));
					}
					
					inquireBulkstockInventoryPageList();
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	//查询融资箱货列表
	var inquireBulkstockInventoryPageList = function() {
		base.fnAjax({
			action: "inquireBulkstockInventoryPageList.json",
			async: false,
			oData: {
				inventoryState: 1,
				financeId: financeId,
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					var tpl;
					if (productType == 3) {
						tpl = $("#bulkstockInventoryTpl1").html();
					} else {
						tpl = $("#bulkstockInventoryTpl").html();
					}
					var html = juicer(tpl, data);
					$("#bulkstockInventoryBody").html(html);
					$.each($("#bulkstockInventoryBody tr"), function() {
						if ($.trim($(this).attr("pickupId")) != 0) {
							$(this).find("td").css("background-color", "#CCC");
							$(this).find("input").attr("disabled", "disabled");
						}
					});
					
					if($(".pickupMethod:checked").val() == 1){
						$(".interestArea").removeClass("none");
						$(".checkeds").prop("checked", true);
						$(".checkeds:disabled").prop("checked", false);
						if ($(".checkeds[disabled!=disable]:checked").length == $(".checkeds[disabled!=disable]").length){
							$("#accountPickup .checkAll").prop("checked", true);
						} else {
							$("#accountPickup .checkAll").prop("checked", false);
						}
						$("#inventoryIds").html('<input type="hidden" name="financeId" value="'+financeId+'" />');
						$.each($(".checkeds:checked"), function(){
							var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
							$("#inventoryIds").append(str);
						});
					}
					
					$("#accountPickup .checkeds").unbind("click").click(function (){
						$.each($(".checkeds[disabled!=disable][checked=checked]"), function(){
							var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
							$("#inventoryIds").append(str);
						});
						if ($(".checkeds[disabled!=disable]:checked").length == $(".checkeds[disabled!=disable]").length){
							$("#accountPickup .checkAll").prop("checked", true);
						} else {
							$("#accountPickup .checkAll").prop("checked", false);
						}
						
						calculateInterest($("#deliveryDate").val());
					});
					
					$("#accountPickup .checkAll").unbind("click").click(function(){
						if ($("#accountPickup .checkAll").prop("checked")) {
							$("#accountPickup .checkeds[disabled!=disabled]").prop("checked", true);
						} else {
							$("#accountPickup .checkeds").prop("checked", false);
						}
						
						$("#inventoryIds").html('<input type="hidden" name="financeId" value="'+financeId+'" />');
						$.each($(".checkeds:checked"), function(){
							var str = '<input name="inventoryIds" type="hidden" value="'+ $(this).attr("inventoryId") +'" />';
							$("#inventoryIds").append(str);
						});
						calculateInterest($("#deliveryDate").val());
					});
				} else {
					//                  base.alert(2,"信息获取失败");
				}
			}
		});
	};

	return {
		init: init
	};
});